<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>权限设置</span>
        </div>
      </template>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="管理平台" name="orchsym">
          <el-button @click="allChecked('orchsym')"
                     v-if="!readonly"
                     style="float: right;margin-right: 30px"
                     type="primary"
          >全选
          </el-button>
          <div class="box-row">
            <template v-for="firstClass in LICENSEENTRIES">
              <template v-for="secClass in firstClass.submenu" :key="secClass.value">
                <el-form-item :label="secClass.label">
                  <el-checkbox-group v-model="defaultCheckList[secClass.value]">
                    <template v-for="per in secClass.permissions" :key="per.value">
                      <el-checkbox :label="per.value" :disabled="readonly">
                        {{ per.label }}
                      </el-checkbox>
                    </template>
                  </el-checkbox-group>
                </el-form-item>
              </template>
            </template>
          </div>
        </el-tab-pane>
        <el-tab-pane label="编排平台" name="runtime" v-if="licenseVersion === 2">
          <el-button v-if="!readonly" @click="allChecked('runtime')" style="float: right;margin-right: 30px"
                     type="primary">全选
          </el-button>
          <div class="box-row">
            <template v-for="firstClass in RUNTIMELICENSEENTRIES">
              <template v-for="secClass in firstClass.submenu" :key="secClass.value">
                <el-form-item :label="secClass.label">
                  <el-checkbox-group v-model="runtimeDefaultCheckList[secClass.value]">
                    <template v-for="per in secClass.permissions" :key="per.value">
                      <el-checkbox :label="per.value" :disabled="readonly">
                        {{ per.label }}
                      </el-checkbox>
                    </template>
                  </el-checkbox-group>
                </el-form-item>
              </template>
            </template>
          </div>
        </el-tab-pane>

        <el-tab-pane label="配置中心" name="ConfigServer" v-if="licenseVersion === 2">
          <el-button v-if="!readonly" @click="allChecked('configServer')" style="float: right;margin-right: 30px"
                     type="primary">全选
          </el-button>
          <div class="box-row">
            <template v-for="firstClass in CONFIGSERVERLICENSEENTRIES">
              <template v-for="secClass in firstClass.submenu" :key="secClass.value">
                <el-form-item :label="secClass.label">
                  <el-checkbox-group v-model="configServerDefaultCheckList[secClass.value]">
                    <template v-for="per in secClass.permissions" :key="per.value">
                      <el-checkbox :label="per.value" :disabled="readonly">
                        {{ per.label }}
                      </el-checkbox>
                    </template>
                  </el-checkbox-group>
                </el-form-item>
              </template>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-affix position="bottom" v-if="!readonly">
      <el-card shadow="never">
        <el-footer style="float: right">
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-footer>
      </el-card>
    </el-affix>
  </div>
</template>

<script lang="ts" setup>
import {
  LICENSEENTRIES,
  licenseChildKeys,
  RUNTIMELICENSEENTRIES,
  CONFIGSERVERLICENSEENTRIES,
  allCheckedKeys
} from "./dict"
import {onBeforeMount, reactive, ref} from "vue"
import type {TabsPaneContext} from "element-plus"

defineOptions({
  name: "Permission"
})

const emits = defineEmits(["submitPermission"])
const props = defineProps({
  readonly: {
    type: Boolean,
    default: false
  },
  propCheckList: {
    type: String,
    default: {}
  },
  licenseVersion: {
    type: Number
  }
})

const activeName = ref("orchsym")
const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event)
}

/** 管理平台默认选中的复选框 */
const defaultCheckList: Record<string, string[]> = reactive({
  apiManage: ["display", "domain", "bodyModel", "project", "apiLog", "apiSearch", "dashboard", "apiUrl"],
  integrationManage: ["display", "d2a"],
  licenseManage: ["read"],
  orgManage: ["read", "create", "edit"],
  userManage: ["read", "create", "edit", "delete", "password", "sourceManage"],
  roleManage: ["read", "create", "edit", "delete", "copy"],
  project: ["display", "d2a", "file", "api", "soap"],
  alarmManage: ["display", "alarmStatistics", "alarmUser", "alarmList", "policy"],
  portalManage: ["display", "preGrantPortal", "partnerManage"],
  partner: ["read", "create", "edit", "delete", "password"],
  envManage: ["display", "envList"],
  cmsManage: [],
  apiSafe: [],
  monitoringCenter: ["display", "overview", "call"],
  actionLog: ["display"],
  test: [],
  operationManagement: [],
  approve: [],
  govern: [],
  cost: [],
})

/** 编排平台默认选中的复选框 */
const runtimeDefaultCheckList: Record<string, string[]> = reactive({
  application: ["display"],
  template: ["display"],
  controllerService: ["display"],
  nodeManage: [],
  traceAlert: ["display"],
  recycleBin: ["display"],
  systemManage: ["display"],
  integrationManage: ["display", "orchsymWeb", "orchsymApi"]
})

/** 配置中心默认选中的复选框 */
const configServerDefaultCheckList: Record<string, string[]> = reactive({
  dashboard: ['display'],
  monitor: ['display', 'SystemResource', 'ConfigOperation', 'RunHistory', 'AlarmNotification'],
  nodeManage: ['display'],
  dataManage: ['display', 'dataSource', 'dataType'],
  templateManage: ['display'],
  systemManage: ['display'],
})


onBeforeMount(() => {
  if (props.propCheckList !== "") {
    const checkedlist = JSON.parse(props.propCheckList)
    if (props.licenseVersion === 1) {
      // 更新 defaultCheckList
      Object.keys(checkedlist).forEach(key => {
        defaultCheckList[key] = checkedlist[key]
      });
    }

    if (props.licenseVersion === 2) {
      // 更新 defaultCheckList
      const coreApi = checkedlist["coreApi"]
      Object.keys(coreApi).forEach(key => {
        defaultCheckList[key] = coreApi[key]
      })

      // 更新 runtimeDefaultCheckList
      const runtime = checkedlist["runtime"]
      Object.keys(runtime).forEach(key => {
        runtimeDefaultCheckList[key] = runtime[key]
      })

      // 更新 configServerDefaultCheckList
      const hdCfgApi = checkedlist["hd-cfg-api"]

      // 如果hdCfgApi没有定义，则将configServerDefaultCheckList置空
      if (hdCfgApi === undefined) {
        Object.keys(configServerDefaultCheckList).forEach((key) => {
          configServerDefaultCheckList[key] = []
        })
      } else {
        // 如果有值，则修改默认值
        Object.keys(hdCfgApi).forEach(key => {
          configServerDefaultCheckList[key] = hdCfgApi[key]
        })
      }
    }
  }
})

/** 处理coreapi需要的数据*/
const translatePermissionToObj = (): Object => {
  interface Result {
    [key: string]: {
      display: boolean
      childs?: {
        [key: string]: boolean
      }
    }
  }

  const result: Result = {
    actionLog: {display: defaultCheckList.actionLog.includes("display") || false}
  }

  Object.keys(defaultCheckList)
    .filter((k) => !["version", "actionLog", "project"].includes(k)) // actionLog/project需要放到apiManage下  所以排除
    .forEach((k) => {
      result[k] = {
        display: defaultCheckList[k].includes("display") || defaultCheckList[k].includes("read"),
        childs: {}
      }
      if (result[k].childs) {
        licenseChildKeys[k].forEach((sk) => {
          //@ts-ignore
          result[k].childs[sk] = defaultCheckList[k].includes(sk)
        })
      }

      if (result[k].childs) {
        //@ts-ignore
        delete result[k].childs.display
      }
    })

  const project = {display: result.apiManage.childs?.project, childs: {} as Record<string, boolean>}

  licenseChildKeys.project.forEach((p) => {
    project.childs[p] = defaultCheckList.project.includes(p)
  })

  //@ts-ignore
  result.apiManage.childs.project = project

  result.system = {
    display:
      result.userManage.display ||
      result.orgManage.display ||
      result.roleManage.display ||
      result.licenseManage.display,
    childs: {
      userManage: result.userManage.display,
      orgManage: result.orgManage.display,
      roleManage: result.roleManage.display,
      licenseManage: result.licenseManage.display
    }
  }
  result.portalManage.childs.partnerManage = result.partner.display
  return result
}

/** 处理runtime需要的数据*/
const nifiTranslatePermissionToObj = (): Object => {
  interface Result {
    [key: string]: {
      childs?: {
        [key: string]: boolean
      }
    }
  }

  const result: Result = {}
  Object.keys(runtimeDefaultCheckList)
    .filter(k => !["nifiVersion"].includes(k)) // version值是字符串/actionLog/project需要放到apiManage下  所以排除
    .forEach((k) => {
      result[k] = {}
      result[k].display = runtimeDefaultCheckList[k].includes("display") || runtimeDefaultCheckList[k].includes("read")
      k === "integrationManage" && runtimeDefaultCheckList[k].forEach((sk) => {
        result[k][sk] = runtimeDefaultCheckList[k].includes(sk)
      })
    })
  return result
}

/** 处理hd-cfg-api需要的数据*/
const configServerTranslatePermissionToObj = (): Object => {
  interface Result {
    [key: string]: {
      childs?: {
        [key: string]: boolean
      }
    }
  }

  const result: Result = {}
  Object.keys(configServerDefaultCheckList)
    .forEach((k) => {
      result[k] = {}
      result[k].display = configServerDefaultCheckList[k].includes("display") || configServerDefaultCheckList[k].includes("read")
      configServerDefaultCheckList[k].forEach((sk) => {
        result[k][sk] = configServerDefaultCheckList[k].includes(sk)
      })
    })
  return result
}

const onSubmit = () => {
  let p
  let checkList
  if (props.licenseVersion === 2) {
    const coreAPI = translatePermissionToObj()
    console.log("coreAPI", coreAPI)
    const nifi = nifiTranslatePermissionToObj()
    const hdCfgApi = configServerTranslatePermissionToObj()
    p = {
      "coreApi": coreAPI,
      "runtime": nifi,
      "hd-cfg-api": hdCfgApi
    }
    checkList = {
      "coreApi": defaultCheckList,
      "runtime": runtimeDefaultCheckList,
      "hd-cfg-api": configServerDefaultCheckList
    }
  } else {
    p = translatePermissionToObj()
    checkList = defaultCheckList
  }
  emits("submitPermission", p, checkList)
}

const allChecked = (svc: string) => {
  Object.keys(allCheckedKeys[svc]).forEach((k) => {
    switch (svc) {
      case "orchsym":
        defaultCheckList[k] = allCheckedKeys[svc][k]
        return
      case "runtime":
        runtimeDefaultCheckList[k] = allCheckedKeys[svc][k]
        return
      case "configServer":
        configServerDefaultCheckList[k] = allCheckedKeys[svc][k]
        return
    }
  })
}
</script>

<style lang="scss" scoped>
.box-row {
  margin-left: 2%;
  margin-right: 5%;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
